package fylder.chat.lib.utils;

import android.media.MediaRecorder;
import android.os.Environment;

import java.io.File;
import java.io.IOException;

/**
 * Created by fylder on 2015/9/10.
 */
public class VoiceUtils {

    private MediaRecorder mMediaRecorder;

    private static VoiceUtils voiceUtils;

    private String voiceFilePath;
    private String voiceFileName = "audio.amr";

    public static VoiceUtils getInstance() {
        if (voiceUtils == null) {
            voiceUtils = new VoiceUtils();
        }
        return voiceUtils;
    }

    public VoiceUtils() {
        initPath();
    }

    public MediaRecorder getmMediaRecorder() {
        return mMediaRecorder;
    }

    private void initPath() {
        voiceFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/demo";
        File file = new File(voiceFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 开始录音
     */
    public void startRecord() {
        try {
            if (mMediaRecorder == null) {
                mMediaRecorder = new MediaRecorder();
            }
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setOutputFile(new File(voiceFilePath, voiceFileName).getAbsolutePath());
            mMediaRecorder.prepare();

            mMediaRecorder.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束录音
     */
    public void stopRecord() {

        if (mMediaRecorder != null) {
            // mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }

    public String getVoicePath() {
        return voiceFilePath + "/" + voiceFileName;
    }
}
